<template>
  <div class="app-container">
    <el-tabs tab-position="top">
      <!-- 基本设置 Tab Pane -->
      <el-tab-pane :label="$t('menu.profile.tabs.information')">
        <div class="w-full">
          <el-card>
            <!-- 头像和昵称部分 -->
            <div class="relative w-100px h-100px flex-center">
              <el-avatar :src="userProfile.avatar" :size="100" />
              <el-button
                type="info"
                class="absolute bottom-0 right-0 cursor-pointer"
                circle
                :icon="Camera"
                size="small"
                @click="triggerFileUpload"
              />
              <input
                ref="fileInput"
                type="file"
                style="display: none"
                accept="image/*"
                @change="handleFileChange"
              />
            </div>
            <div class="mt-5 ml-5">
              {{ userProfile.nickname }}
              <el-icon
                class="align-middle cursor-pointer"
                @click="handleOpenDialog(DialogType.ACCOUNT)"
              >
                <Edit />
              </el-icon>
            </div>
            <!-- 用户信息描述 -->
            <el-descriptions border :column="1" class="mt-10" label-width="150">
              <!-- 用户名 -->
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><User /></el-icon>
                  {{ $t('menu.admin.user.field.username') }}
                </template>
                {{ userProfile.username }}
                <el-icon
                  v-if="userProfile.gender === 1"
                  class="align-middle color-blue"
                >
                  <Male />
                </el-icon>
                <el-icon v-else class="align-middle color-pink">
                  <Female />
                </el-icon>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Phone /></el-icon>
                  {{ $t('menu.admin.user.field.phone') }}
                </template>
                {{ userProfile.mobile }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Message /></el-icon>
                  {{ $t('menu.admin.user.field.email') }}
                </template>
                {{ userProfile.email }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <SvgIcon icon-class="tree" />
                  {{ $t('menu.admin.user.field.dept_id') }}
                </template>
                {{ userProfile.deptName }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <SvgIcon icon-class="role" />
                  {{ $t('menu.profile.field.role') }}
                </template>
                {{ userProfile.roleNames }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle"><Timer /></el-icon>
                  {{ $t('common.field.create_time') }}
                </template>
                {{ userProfile.createTime }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </el-tab-pane>

      <!-- 安全设置  -->
      <el-tab-pane :label="$t('menu.profile.tabs.security')">
        <el-card>
          <!-- 账户密码 -->
          <el-row>
            <el-col :span="16">
              <div class="font-bold">
                {{ $t('menu.profile.security.change_password') }}
              </div>
              <div class="text-14px mt-2">
                {{ $t('menu.profile.security.change_password_hint') }}
                <el-button
                  type="primary"
                  plain
                  class="ml-5"
                  @click="() => handleOpenDialog(DialogType.PASSWORD)"
                >
                  {{ $t('common.action.change') }}
                </el-button>
              </div>
            </el-col>
          </el-row>
          <!-- 绑定手机 -->
          <div class="mt-5">
            <div class="font-bold">绑定手机</div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.mobile">
                {{
                  $t('menu.profile.security.bind_mobile_hint_no_bind', {
                    mobile: userProfile.mobile,
                  })
                }}
              </span>
              <span v-else>
                {{ $t('menu.profile.security.bind_mobile_hint_no_bind') }}
              </span>
              <el-button
                v-if="userProfile.mobile"
                type="primary"
                plain
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)"
              >
                {{ $t('common.action.change') }}
              </el-button>
              <el-button
                v-else
                type="primary"
                plain
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)"
              >
                {{ $t('common.action.bind') }}
              </el-button>
            </div>
          </div>
          <!-- 绑定邮箱 -->
          <div class="mt-5">
            <div class="font-bold">
              {{ $t('menu.profile.security.bind_email') }}
            </div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.email">
                {{
                  $t('menu.profile.security.bind_email_hint_bind', {
                    email: userProfile.email,
                  })
                }}
              </span>
              <span v-else>
                {{ $t('menu.profile.security.bind_email_hint_no_bind') }}
              </span>
              <el-button
                v-if="userProfile.email"
                type="primary"
                plain
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)"
              >
                {{ $t('common.action.change') }}
              </el-button>
              <el-button
                v-else
                type="primary"
                plain
                class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)"
              >
                {{ $t('common.action.bind') }}
              </el-button>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 统一弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="500"
      @close="handleDialogClose"
    >
      <!-- 动态渲染子组件 -->
      <component
        :is="currentFormComponent"
        ref="currentFormRef"
        v-if="dialog.visible && currentFormComponent"
        :initial-data="getInitialDataForForm(dialog.type)"
        @submit-success="handleFormSubmitSuccess"
        @submit-cancel="handleFormSubmitCancel"
      />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialog.visible = false">
            {{ $t('common.action.cancel') }}
          </el-button>
          <el-button type="primary" @click="handleDialogConfirm">
            {{ $t('common.action.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, computed, markRaw, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import {
  Camera,
  Edit,
  User,
  Male,
  Female,
  Phone,
  Message,
  Timer,
} from '@element-plus/icons-vue';
import { smartTranslate as $t, transPlaceholder as $p } from '@/lang';
import API from '@/api/admin/profile';
import UploadAPI from '@/api/admin/upload';

// 导入子组件
import AccountForm from './AccountForm.vue';
import PasswordForm from './PasswordForm.vue';
import MobileForm from './MobileForm.vue';
import EmailForm from './EmailForm.vue';

const userProfile = ref({});
const fileInput = ref(null);
const content = ref(null);

const DialogType = {
  ACCOUNT: 'account',
  PASSWORD: 'password',
  MOBILE: 'mobile',
  EMAIL: 'email',
};

const dialog = reactive({
  visible: false,
  title: '',
  type: '',
});

const currentFormRef = ref(null);

// 根据dialog.type动态选择要渲染的组件
const currentFormComponent = computed(() => {
  switch (dialog.type) {
    case DialogType.ACCOUNT:
      return markRaw(AccountForm);
    case DialogType.PASSWORD:
      return markRaw(PasswordForm);
    case DialogType.MOBILE:
      return markRaw(MobileForm);
    case DialogType.EMAIL:
      return markRaw(EmailForm);
    default:
      return null;
  }
});

// 获取传递给子组件的初始数据
const getInitialDataForForm = (type) => {
  if (type === DialogType.ACCOUNT) {
    return { ...userProfile.value };
  }
  return {};
};

/**
 * 打开弹窗
 * @param type 弹窗类型
 */
const handleOpenDialog = (type) => {
  dialog.type = type;
  dialog.visible = true;
  switch (type) {
    case DialogType.ACCOUNT:
      dialog.title = $t('menu.profile.security.account_info');
      break;
    case DialogType.PASSWORD:
      dialog.title = $t('menu.profile.security.change_password');
      break;
    case DialogType.MOBILE:
      dialog.title = $t('menu.profile.security.bind_mobile');
      break;
    case DialogType.EMAIL:
      dialog.title = $t('menu.profile.security.bind_email');
      break;
  }
};

// 弹窗确认按钮点击事件
const handleDialogConfirm = () => {
  if (currentFormRef.value && currentFormRef.value.submitForm) {
    currentFormRef.value.submitForm();
  } else {
    console.warn('当前表单组件没有 submitForm 方法');
    dialog.visible = false;
  }
};

// 子组件提交成功事件处理
const handleFormSubmitSuccess = () => {
  dialog.visible = false;
  loadUserProfile(); // 刷新用户数据
};

// 子组件取消事件处理
const handleFormSubmitCancel = () => {
  dialog.visible = false;
};

// 弹窗关闭时的回调，用于重置子组件状态
const handleDialogClose = () => {
  if (currentFormRef.value && currentFormRef.value.resetForm) {
    currentFormRef.value.resetForm();
  }
};

// 头像上传相关方法
const triggerFileUpload = () => {
  fileInput.value.click();
};

const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    ElMessage.error('请选择图片文件');
    return;
  }

  // 验证文件大小（例如限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error('图片大小不能超过2MB');
    return;
  }

  try {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('edit', 1);

    // 上传头像
    const { data } = await UploadAPI.upload(formData);
    console.log('data', data);

    // 更新用户头像
    await API.updateProfile({
      id: userProfile.value.id,
      avatar: data.url,
    });

    ElMessage.success('头像上传成功');
    ElMessage.success(
      $t('common.message.success.upload', {
        field: $t('menu.profile.field.avatar'),
      }),
    );

    loadUserProfile(); // 刷新用户数据
  } catch (error) {
    console.error('头像上传失败:', error);
  } finally {
    // 清空文件输入框
    event.target.value = '';
  }
};

// 加载用户资料
const loadUserProfile = async () => {
  try {
    const { data } = await API.getProfile();
    userProfile.value = data;
  } catch (error) {
    console.error('获取用户资料失败:', error);
    // 模拟数据，实际项目中应该处理错误
    userProfile.value = {
      id: 1,
      nickname: '测试用户',
      gender: 1,
      username: 'testuser',
      mobile: '13812345678',
      email: 'test@example.com',
      deptName: '研发部',
      roleNames: '管理员',
      createTime: '2023-01-01 10:00:00',
      avatar:
        'https://cube.elemecdn.com/0/88/03b0dff428be2a5e76909c6829b1acefd.jpeg',
    };
  }
};

// 页面加载时获取用户资料
onMounted(() => {
  loadUserProfile();
});

// 组件选项
defineOptions({
  name: 'AdminBaseProfile',
  inheritAttrs: false,
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.w-100px {
  width: 100px;
}

.h-100px {
  height: 100px;
}

.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.relative {
  position: relative;
}

.absolute {
  position: absolute;
}

.bottom-0 {
  bottom: 0;
}

.right-0 {
  right: 0;
}

.mt-5 {
  margin-top: 1.25rem;
}

.ml-5 {
  margin-left: 1.25rem;
}

.mt-10 {
  margin-top: 2.5rem;
}

.mt-2 {
  margin-top: 0.5rem;
}

.w-full {
  width: 100%;
}

.font-bold {
  font-weight: bold;
}

.text-14px {
  font-size: 14px;
}

.align-middle {
  vertical-align: middle;
}

.cursor-pointer {
  cursor: pointer;
}

.color-blue {
  color: #409eff;
}

.color-pink {
  color: #f56c6c;
}
</style>
